#include "MyTcpSocket.h"
#include "protocol.h"

MyTcpSocket::MyTcpSocket(QObject *parent)
    : QTcpSocket{parent}
{
    connect(this, SIGNAL(readyRead()), this, SLOT(recvMsg()));

}

void MyTcpSocket::recvMsg()
{
    uint pduLen = 0;
    this->read((char *)&pduLen, sizeof(uint)); // 前4个字节保存的是长度
    PDU *pdu = mkPDU(pduLen - sizeof(PDU));
    this->read((char *)(pdu+sizeof(uint)), pduLen-sizeof(uint)); // 前4个字节(1个uint的长度)是长度，所以从4个字节(1个uint的长度)之后开始读，所以是pdu+sizeof(uint)

    // 数据完整性校验
    int msgLen = pduLen - sizeof(PDU);
    if(msgLen != pdu->usMsgLen){
        qDebug() << "msgLen error";
    }

    QString strData;
    strData = QString::fromLocal8Bit(pdu->usData);
    qDebug() << "pduLen = " << pduLen << "; usData = " << strData;

    free(pdu);
    pdu = NULL;
}
